/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.izu.mytruco.game;

import com.izu.mytruco.deck.Card;
import com.izu.mytruco.deck.Deck;
import com.izu.mytruco.deck.Suit;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 *
 * @author ademarizu
 */
public class Game {

    protected Integer roundNumber;
    protected Map<String, Player> players;
    protected List<Card> round;
    protected Card bestCard;
    protected Player winningRound;
    protected Card turnedCard;
    protected boolean isTie;
    protected static final Suit[] suitesOrder = {Suit.DIAMONDS, Suit.SPADES, Suit.HEARTS, Suit.CLUBS};


    public void playCard(String playerId, int cardPosition, boolean turnedDown) {
        Player player = players.get(playerId);
        Card card = player.getCard(cardPosition);
        if (bestCardOnTable(card)) {
            winningRound = player;
        }
        round.add(card);
    }

    protected boolean bestCardOnTable(Card card) {
        //Should be the first card
        if (bestCard == null) {
            bestCard = card;
        } else if (isManilha(bestCard) || isManilha(card)){
            if (isManilha(bestCard) && isManilha(card)) {
                bestCard = compareSuites(bestCard.getSuit(), card.getSuit()) > 0 ? bestCard : card;
            } else {
                bestCard = isManilha(bestCard) ? bestCard : card;
            }
        } else {
            if (card.getValue() == bestCard.getValue()) {
                isTie = true;
            } else {
                bestCard = card.getValue() > bestCard.getValue() ? card : bestCard;
            }
        }
        return bestCard.equals(card);
    }

    protected boolean isManilha(Card card) {
        boolean isManilha = false;
        if (turnedCard.getValue() == Deck.LAST_VALUE) {
            isManilha = card.getValue() == Deck.FIRST_VALUE;
        } else {
            isManilha = card.getValue() == turnedCard.getValue() + 1;
        }
        return isManilha;
    }

    protected Integer compareSuites(Suit firstSuit, Suit secondSuit) {
        Integer firstValue = Arrays.binarySearch(suitesOrder, firstSuit);
        Integer secondValue = Arrays.binarySearch(suitesOrder, secondSuit);
        return firstValue.compareTo(secondValue);
    }
}
